package com.bysj.system.controller;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.codec.binary.Base64;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.bysj.system.domain.ContractTemplate;
import com.bysj.system.service.IContractTemplateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 合同模板管理Controller
 *
 * @author bysj
 * @date 2024-02-03
 */
@RestController
@RequestMapping("/system/template")
public class ContractTemplateController extends BaseController {
    @Value("${ruoyi.profile}")
    private String basepath;
    @Autowired
    private IContractTemplateService contractTemplateService;

    /**
     * 查询合同模板管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:template:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContractTemplate contractTemplate) {
        startPage();
        List<ContractTemplate> list = contractTemplateService.selectContractTemplateList(contractTemplate);
        return getDataTable(list);
    }

    /**
     * 导出合同模板管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:template:export')")
    @Log(title = "合同模板管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractTemplate contractTemplate) {
        List<ContractTemplate> list = contractTemplateService.selectContractTemplateList(contractTemplate);
        ExcelUtil<ContractTemplate> util = new ExcelUtil<ContractTemplate>(ContractTemplate.class);
        util.exportExcel(response, list, "合同模板管理数据");
    }

    /**
     * 获取合同模板管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:template:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(contractTemplateService.selectContractTemplateById(id));
    }

    /**
     * 新增合同模板管理
     */
    @PreAuthorize("@ss.hasPermi('system:template:add')")
    @Log(title = "合同模板管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractTemplate contractTemplate) {
        return toAjax(contractTemplateService.insertContractTemplate(contractTemplate));
    }

    /**
     * 修改合同模板管理
     */
    @PreAuthorize("@ss.hasPermi('system:template:edit')")
    @Log(title = "合同模板管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractTemplate contractTemplate) {
        return toAjax(contractTemplateService.updateContractTemplate(contractTemplate));
    }

    /**
     * 删除合同模板管理
     */
    @PreAuthorize("@ss.hasPermi('system:template:remove')")
    @Log(title = "合同模板管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(contractTemplateService.deleteContractTemplateByIds(ids));
    }

    //    单独写一个下载啊文件的请求
//    http://localhost/system/template/downloadTemplate
//    http://localhost/dev-api/system/template/list?pageNum=1&pageSize=1
//    D:\\ruoyi\\uploadPath\\upload\\2024\\02\\03

    @GetMapping("/downloadTemplate")
    public AjaxResult downloadTemplate(@RequestParam String fileName, HttpServletResponse response) throws IOException {
        // 拼接文件路径
        String filePath = basepath + fileName.replace("/profile", "");
        String fileNameWithoutExtension = getFileNameWithoutExtension(filePath);

        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        byte[] base64Bytes = Base64.encodeBase64(fileContent);


        return AjaxResult.success(fileNameWithoutExtension, new String(base64Bytes));
    }
    private String getFileNameWithoutExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0) {
            return fileName.substring(0, lastDotIndex);
        } else {
            return fileName;
        }
    }
}
